package com.hnxxxy.oa.information.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hnxxxy.oa.information.mapper.MessageToUserMapper;
import com.hnxxxy.oa.information.mapper.ReadCommonMessageMapper;
import com.hnxxxy.oa.information.model.MessageToUserDO;
import com.hnxxxy.oa.information.model.ReadCommonMessageDO;
import com.hnxxxy.oa.information.service.ReadCommonMessageService;
import com.hnxxxy.oa.system.constant.UserConstant;
import com.hnxxxy.oa.system.model.SysUserDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户已读消息表 服务实现类
 * </p>
 *
 * @author zqh
 * @since 2022-04-24
 */
@Service
@Slf4j
public class ReadCommonMessageServiceImpl implements ReadCommonMessageService {

    @Autowired
    private ReadCommonMessageMapper readCommonMessageMapper;

    @Autowired
    private MessageToUserMapper messageToUserMapper;

    /**
     * 消息已读
     * @param messageId
     */
    @Override
    public void confirm(int messageId) {

        // TODO: 如何判断我是第一次查看消息

        SysUserDO user = (SysUserDO) StpUtil.getSession().get(UserConstant.SESSION_USER_KEY);
        ReadCommonMessageDO readCommonMessageDO = new ReadCommonMessageDO();
        readCommonMessageDO.setUserId(user.getId());
        readCommonMessageDO.setMessageId(messageId);
        readCommonMessageDO.setCreateTime(LocalDateTime.now());

        MessageToUserDO messageToUserDO = new MessageToUserDO();
        messageToUserDO.setIsRead(1);

        int rows = readCommonMessageMapper.insert(readCommonMessageDO);
        log.info("rows={},readCommonMessageDO={}", rows,readCommonMessageDO);

        int updateRows = messageToUserMapper.update(messageToUserDO, new QueryWrapper<MessageToUserDO>().eq("message_id", messageId).eq("to_user_id", user.getId()));

        log.info("updateRows={},messageToUserDO={}", updateRows,messageToUserDO);

    }
}
